package com.ygqh.baby.controller.admin;

import java.util.Date;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ygqh.baby.ao.Message;
import com.ygqh.baby.po.YgCategory;
import com.ygqh.baby.po.YgGroup;
import com.ygqh.baby.service.YgCategoryService;
import com.ygqh.baby.service.YgGroupService;
import com.ygqh.baby.service.YgProductService;

@Controller
@RequestMapping("admin/category")
public class CategoryController extends BaseController<Object, java.lang.Long> {
	
	@Autowired
	private YgCategoryService ygCategoryService;
	@Autowired
	private YgGroupService ygGroupService;
	@Autowired
	private YgProductService ygProductService;
	
	@RequestMapping(value = "searchCategory", method = RequestMethod.GET)
	@ResponseBody
	public Message searchCategory() {
		return Message.success(ygCategoryService.find());
	}

	@RequestMapping(value = "saveCategory", method = RequestMethod.POST)
	@ResponseBody
	public Message saveCategory(YgCategory category) {
		if (ygCategoryService.validateCategoryName(category.getParentId(), category.getCategoryName(), null)) {
			category.setId(null);
			category.setCreateBy(getSession().getTrueName());
			category.setCreateTime(new Date());
			ygCategoryService.save(category);
			return Message.success(category);
		}
		return Message.error("同级分类下名称重复", null);
	}

	@RequestMapping(value = "renameCategory", method = RequestMethod.POST)
	@ResponseBody
	public Message renameCategory(Long id, Long parentId, String categoryName) {
		if (ygCategoryService.validateCategoryName(parentId, categoryName, id)) {
			YgCategory record = new YgCategory();
			record.setId(id);
			record.setCategoryName(categoryName);
			record.setUpdateTime(new Date());
			record.setUpdateBy(getSession().getTrueName());
			ygCategoryService.update(record);
			ygProductService.updateCategoryNamesByCategoryId(id);
			return SUCCESS_MESSAGE;
		}
		return Message.error("同级分类下名称重复", null);
	}

	@RequestMapping(value = "delCategory", method = RequestMethod.POST)
	@ResponseBody
	public Message delCategory(Long id) {
		List<YgCategory> categoryList = ygCategoryService.findByParentId(id);
		if (CollectionUtils.isNotEmpty(categoryList)) {
			return Message.error("该分类下有子级分类", null);
		}
		List<YgGroup> groupList = ygGroupService.findByCategoryId(id);
		if (CollectionUtils.isNotEmpty(groupList)) {
			return Message.error("该分类下有商品款式信息", null);
		}
		ygCategoryService.deleteSoft(id);
		return SUCCESS_MESSAGE;
	}

}
